package com.chlitina.store.modules.cash.web;

import java.util.ArrayList;
import java.util.List;
import java.util.Map;
import java.util.Set;

import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import javax.servlet.http.HttpSession;

import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Controller;
import org.springframework.ui.Model;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.ResponseBody;

import com.chlitina.store.common.config.Global;
import com.chlitina.store.common.mapper.JsonMapper;
import com.chlitina.store.common.utils.StoreProductUtils;
import com.chlitina.store.common.web.BaseController;
import com.chlitina.store.modules.base.entity.Customer;
import com.chlitina.store.modules.base.entity.StoreProduct;
import com.chlitina.store.modules.base.service.StoreProductService;
import com.chlitina.store.modules.cash.model.GiftCart;
import com.chlitina.store.modules.cash.model.Member;
import com.chlitina.store.modules.cash.model.StoreProductCart;
import com.chlitina.store.modules.cash.service.NomemberService;
import com.chlitina.store.modules.cash.utils.StoreCashUtils;
import com.chlitina.store.modules.employee.dao.EmployeeDao;
import com.chlitina.store.modules.employee.entity.Employee;
import com.chlitina.store.modules.sys.utils.StoreUtils;
import com.google.common.collect.Lists;
import com.google.common.collect.Maps;
import com.google.common.collect.Sets;

/**
 * Crash Controller
 * 
 * @author Songsong.xu
 * @version 2013-3-23
 */
@Controller
@RequestMapping(value = Global.ADMIN_PATH + "/cash/member/gift")
public class GiftController extends BaseController {
	@Autowired
	private NomemberService nomemberService;
	@Autowired
	private EmployeeDao employeeDao;
	@Autowired
	private StoreProductService storeProductService;

	public static interface KEY {
		String KEY_MEMBER = "member";
		String KEY_MESSAGE = "message";
	}

	public static interface URI {
		String URI_MEMBER_CONSUME = "modules/cash/cashMemberConsume";
		String URI_MEMBER_DETAIL = "modules/cash/cashMemberDetail";
		String URI_MEMBER_SHOPPING_DETAIL = "modules/cash/shoppingDetail";
		String URI_MEMBER_SHOPPING_DETAIL_DOCARE = "modules/cash/shoppingDetailDocare";
		String URI_MEMBER_SHOPPING_DETAIL_PRODUCT = "modules/cash/shoppingDetailProduct";
		String URI_MEMBER_SHOPPING_DETAIL_RECHARGE = "modules/cash/shoppingDetailRecharge";
		String URI_MEMBER_SHOPPING_PAYMENT = "modules/cash/shoppingPayment";
		String URI_MEMBER_CARDS = "modules/cash/cashMemberCards";
		String URI_MEMBER_CARDS_NEW = "modules/cash/cashMemberCardsNew";
		String URI_MEMBER_SHOPPING_NEWCARDS = "modules/cash/cashMemberShoppingNewCards";
		String URI_MEMBER_BUY_PRODUCT_MAINPAGE = "modules/cash/memberBuyProductMainPage";

		String URI_MEMBER_DO_CARE = "modules/cash/cashMemberDoCare";
		String URI_MEMVER_SHOOPING_NEWCARDS_PAYMENT = "modules/cash/newcardsPayment";
		String URI_MEMVER_SHOOPING_PRODUCT_PAYMENT = "modules/cash/productPayment";
		String URI_MEMVER_SHOOPING_RECHARGE_PAYMENT = "modules/cash/rechargePayment";

		String URI_MEMBER_GIFT_PRODUCT_STORE_PAGE = "modules/cash/memberGiftStoreProductPage";
		String URI_MEMBER_GIFT_PRODUCT_SYSTEM_PAGE = "modules/cash/memberGiftSystemProductPage";

	}

	@RequestMapping(value = { "systemProduct/page" })
	public String systemProductPage(HttpServletRequest request,
			HttpServletResponse response, Model model) {
		Member member = StoreUtils.getMember();
		if (member == null) {
			model.addAttribute("message", "会员状态丢失");
			return "redirect:" + Global.ADMIN_PATH + "/cash/member";
		}
		model.addAttribute("systemProduct", new StoreProductCart());
		updateEmployee(request);
		return URI.URI_MEMBER_GIFT_PRODUCT_SYSTEM_PAGE;
	}

	private Member getMember() {
		return StoreUtils.getMember();
	}

	@RequestMapping(value = { "storeProduct/page" })
	public String storeProductPage(HttpServletRequest request,
			HttpServletResponse response, Model model) {
		Member member = getMember();
		if (member == null) {
			model.addAttribute("message", "会员状态丢失");
			return "redirect:" + Global.ADMIN_PATH + "/cash/member";
		}
		model.addAttribute(KEY.KEY_MEMBER, member);
		updateEmployee(request);
		model.addAttribute("storeProduct", new StoreProductCart());
		return URI.URI_MEMBER_GIFT_PRODUCT_STORE_PAGE;
	}

	@ResponseBody
	@RequestMapping(value = { "systemProduct/clientDeleteProduct","storeProduct/clientDeleteProduct" })
	public String clientDeleteProduct(HttpServletRequest request,
			HttpServletResponse response, String productID, String type) {
		boolean result = true;
		String message = "";
		if (Types.system.equals(type) || Types.storeself.equals(type)) {
			Member member = getMember();
			if (member == null) {
				result = false;
				message = "状态丢失";
			} else {
				GiftCart giftCart = member.getGiftCart();
				StoreProduct storeProduct = storeProductService.get(Long
						.parseLong(productID));
				if (storeProduct == null) {
					result = false;
					message = "错误的产品编号，未找到匹配产品";
				} else {
					if (Types.system.equals(type)) {
						giftCart.deleteSystemProduct(storeProduct.getId()
								.intValue());
					} else {
						giftCart.deleteStoreProduct(storeProduct.getId()
								.intValue());
					}
					result = true;
					message = "删除成功";
				}
				member.updateMenuState();
			}
		} else {
			result = false;
			message = "错误的产品类型";
		}

		Set<Map<String, Object>> set = Sets.newHashSet();
		Map<String, Object> map = Maps.newHashMap();
		map.put("id", productID);
		map.put("result", result);
		map.put("message", message);
		set.add(map);
		System.err.println(JsonMapper.getInstance().toJson(set));
		return JsonMapper.getInstance().toJson(set);
	}

	@ResponseBody
	@RequestMapping(value = { "systemProduct/clientAddProduct","storeProduct/clientAddProduct" })
	public String clientAddProduct(HttpServletRequest request,
			HttpServletResponse response, String productID, String employeeID,
			String amount, String type) {
		boolean result = true;
		String message = "";
		if (Types.system.equals(type) || Types.storeself.equals(type)) {
			Member member = getMember();
			if (member == null) {
				result = false;
				message = "状态丢失";
			} else {
				GiftCart giftCart = member.getGiftCart();
				StoreProduct storeProduct = storeProductService.get(Long
						.parseLong(productID));
				if (storeProduct == null) {
					result = false;
					message = "错误的产品编号，未找到匹配产品";
				} else {
					List<StoreProductCart> products = null;
					if (Types.system.equalsIgnoreCase(type)) {
						products = giftCart.getSystemProducts();

					} else {
						products = giftCart.getStoreProducts();
					}
					if (StoreCashUtils.exist(products, storeProduct.getId())) {
						result = false;
						message = "不能重复添加产品";
					} else {
						Employee employee = employeeDao.findOne(Long
								.parseLong(employeeID));
						if (employee == null) {
							result = false;
							message = "错误的员工编号，未找到匹配员工";
						} else {
							StoreProductCart cart = new StoreProductCart();
							cart.setEmployee(employee);
							cart.setCount(Integer.parseInt(amount));
							cart.setStoreProduct(storeProduct);
							products.add(cart);
							result = true;
							message = "添加成功";
						}
					}
					member.updateMenuState();
				}
			}
		} else {
			result = false;
			message = "错误的产品类型";
		}

		Set<Map<String, Object>> set = Sets.newHashSet();
		Map<String, Object> map = Maps.newHashMap();
		map.put("id", productID);
		map.put("result", result);
		map.put("message", message);
		set.add(map);
		System.err.println(JsonMapper.getInstance().toJson(set));
		return JsonMapper.getInstance().toJson(set);
	}

	
	@ResponseBody
	@RequestMapping(value = { "systemProduct/clientLoadingProduct","storeProduct/clientLoadingProduct"  })
	public String clientLoadingProduct(HttpServletRequest request,
			HttpServletResponse response, String type) {
		List<StoreProduct> storeProducts = null;
		if (Types.system.equalsIgnoreCase(type)) {
			storeProducts = nomemberService.findSystemProducts();
		} else if (Types.storeself.equalsIgnoreCase(type)) {
			storeProducts = nomemberService.findStoreSelfProducts();
		} else {

		}
		List<Map<String, Object>> set = Lists.newArrayList();
		Map<String, Object> map = null;
		Member member = getMember();
		if (member != null) {
			GiftCart giftCart = member.getGiftCart();
			map = Maps.newHashMap();
			map.put("result", true);
			List<StoreProductCart> products =null;
			if (Types.system.equalsIgnoreCase(type)) {
				products = giftCart.getSystemProducts();
			} else if (Types.storeself.equalsIgnoreCase(type)) {
				products = giftCart.getStoreProducts();
			} else {

			}
			List<Map<String, Object>> addedSet = Lists.newArrayList();
			for (StoreProductCart storeProductCart : products) {
				map = Maps.newHashMap();
				map.put("id", storeProductCart.getStoreProduct().getId());
				addedSet.add(map);
			}
			System.err.println(JsonMapper.getInstance().toJson(addedSet));
			map.put("addedProducts", JsonMapper.getInstance().toJson(addedSet));
			set.add(map);

			if (storeProducts != null) {
				for (StoreProduct storeProduct : storeProducts) {
					if (storeProduct.getAmount() < 1) {
						continue;
					}
					map = Maps.newHashMap();
					map.put("id", storeProduct.getId());
					map.put("amount", storeProduct.getAmount());
					map.put("category",
							StoreProductUtils.getCategory(storeProduct));
					map.put("name", StoreProductUtils.getName(storeProduct));
					map.put("retailPrice",
							StoreProductUtils.getRetailPrice(storeProduct));
					map.put("spec", StoreProductUtils.getSpec(storeProduct));
					set.add(map);
				}
			}

		} else {
			map = Maps.newHashMap();
			map.put("result", false);
			map.put("message", "状态丢失");
			set.add(map);
		}

		System.err.println(JsonMapper.getInstance().toJson(set));
		return JsonMapper.getInstance().toJson(set);
	}

	@RequestMapping(value = { "systemProduct/add" })
	public String addSystemProduct(StoreProductCart product,
			HttpServletRequest request, HttpServletResponse response,
			Model model) {
		Member member = getMember();
		if (member == null) {
			model.addAttribute("message", "会员状态丢失");
			return "redirect:" + Global.ADMIN_PATH + "/cash/member";
		}
		model.addAttribute(KEY.KEY_MEMBER, member);
		GiftCart giftCart = member.getGiftCart();
		if (product.getStoreProduct() == null
				|| product.getStoreProduct().getId() == null) {
			model.addAttribute("message", "错误的请求");
			model.addAttribute("systemProduct", new StoreProductCart());
			return URI.URI_MEMBER_GIFT_PRODUCT_SYSTEM_PAGE;
		}
		product.setStoreProduct(storeProductService.get(product
				.getStoreProduct().getId()));
		product.setEmployee(employeeDao.findOne(product.getEmployee().getId()
				.longValue()));
		giftCart.getSystemProducts().add(product);
		member.updateMenuState();

		model.addAttribute("systemProduct", new StoreProductCart());
		return URI.URI_MEMBER_GIFT_PRODUCT_SYSTEM_PAGE;
	}

	@RequestMapping(value = { "systemProduct/delete" })
	public String deleteProduct(HttpServletRequest request,
			HttpServletResponse response, Model model) {
		Member member = getMember();
		if (member == null) {
			model.addAttribute("message", "会员状态丢失");
			return "redirect:" + Global.ADMIN_PATH + "/cash/member";
		}
		GiftCart giftCart = member.getGiftCart();
		model.addAttribute(KEY.KEY_MEMBER, member);
		String parameter = request.getParameter("id");
		if (parameter != null && !parameter.isEmpty()) {
			int id = Integer.parseInt(parameter);
			giftCart.deleteSystemProduct(id);
		}
		model.addAttribute("systemProduct", new StoreProductCart());
		return URI.URI_MEMBER_GIFT_PRODUCT_SYSTEM_PAGE;
	}

	@RequestMapping(value = { "storeProduct/add" })
	public String addStoreProduct(StoreProductCart product,
			HttpServletRequest request, HttpServletResponse response,
			Model model) {
		Member member = getMember();
		if (member == null) {
			model.addAttribute("message", "会员状态丢失");
			return "redirect:" + Global.ADMIN_PATH + "/cash/member";
		}
		GiftCart giftCart = member.getGiftCart();
		if (product.getStoreProduct() == null
				|| product.getStoreProduct().getId() == null) {
			model.addAttribute("message", "错误的请求");
			model.addAttribute("systemProduct", new StoreProductCart());
			return URI.URI_MEMBER_GIFT_PRODUCT_STORE_PAGE;
		}
		product.setStoreProduct(storeProductService.get(product
				.getStoreProduct().getId()));
		product.setEmployee(employeeDao.findOne(product.getEmployee().getId()
				.longValue()));
		model.addAttribute("storeProduct", new StoreProductCart());
		model.addAttribute(KEY.KEY_MEMBER, member);
		giftCart.getStoreProducts().add(product);
		member.updateMenuState();
		return URI.URI_MEMBER_GIFT_PRODUCT_STORE_PAGE;
	}

	@ResponseBody
	@RequestMapping(value = { "systemProduct/canBuyProduct",
			"storeProduct/canBuyProduct" })
	public String canBuyProduct(String productID, String count) {
		String[] resut = { "false", "0" };
		try {
			long required = Long.parseLong(count);
			long id = Long.parseLong(productID);
			long amount = StoreCashUtils.currentProductAmount(getMember(), id);
			if (amount >= required) {
				resut[0] = "" + true;
				resut[1] = amount + "";
				return JsonMapper.getInstance().toJson(resut);
			} else {
				resut[1] = amount + "";
				return JsonMapper.getInstance().toJson(resut);
			}
		} catch (Exception e) {
			return JsonMapper.getInstance().toJson(resut);
		}
	}

	boolean contains(List<Long> added, Long id) {
		for (Long value : added) {
			if (value.longValue() == id.longValue()) {
				return true;
			}
		}
		return false;
	}

	private List<StoreProduct> getSystemProductList(Member member) {
		List<StoreProduct> systemStoreProducts = nomemberService
				.findSystemProducts();
		GiftCart giftCart = member.getGiftCart();
		List<Long> added = new ArrayList<Long>();
		List<StoreProductCart> systemProducts = giftCart.getSystemProducts();
		for (StoreProductCart productCart : systemProducts) {
			added.add(productCart.getStoreProduct().getId());
		}

		List<StoreProduct> result = new ArrayList<StoreProduct>();
		for (StoreProduct sp : systemStoreProducts) {
			if (contains(added, sp.getId())) {
				continue;
			}
			if (sp.getAmount() < 1) {
				continue;
			}
			result.add(sp);
		}
		return result;
	}

	private List<StoreProduct> getSelfProductList(Member member) {
		List<StoreProduct> storeSelfProducts = nomemberService
				.findStoreSelfProducts();
		GiftCart giftCart = member.getGiftCart();
		List<Long> added = new ArrayList<Long>();
		List<StoreProductCart> storeProducts = giftCart.getStoreProducts();
		for (StoreProductCart productCart : storeProducts) {
			if (productCart.getStoreProduct().getProduct_type() == StoreProduct.TYPE_SELF) {
				added.add(productCart.getStoreProduct().getId());
			}
		}
		List<StoreProduct> result = new ArrayList<StoreProduct>();
		for (StoreProduct sp : storeSelfProducts) {
			if (contains(added, sp.getId())) {
				continue;
			}
			if (sp.getAmount() < 1) {
				continue;
			}
			result.add(sp);
		}
		return result;
	}

	@RequestMapping(value = { "storeProduct/delete" })
	public String deleteStoreProduct(Customer customer,
			HttpServletRequest request, HttpServletResponse response,
			Model model) {
		Member member = getMember();
		if (member == null) {
			model.addAttribute("message", "会员状态丢失");
			return "redirect:" + Global.ADMIN_PATH + "/cash/member";
		}
		model.addAttribute(KEY.KEY_MEMBER, member);
		GiftCart giftCart = member.getGiftCart();
		String parameter = request.getParameter("id");
		if (parameter != null && !parameter.isEmpty()) {
			int id = Integer.parseInt(parameter);
			giftCart.deleteStoreProduct(id);
		}
		model.addAttribute("storeProduct", new StoreProductCart());
		member.updateMenuState();
		return URI.URI_MEMBER_GIFT_PRODUCT_STORE_PAGE;
	}

	public void updateEmployee(HttpServletRequest request) {
		HttpSession session = request.getSession();
		Object attribute = session.getAttribute("employees");
		if (attribute == null) {
			session.setAttribute("employees",
					employeeDao.findListByStore(StoreUtils.getStore().getId(),Employee.STATUS_WORKING));
		} else if (attribute instanceof List<?>) {
			List<?> a = (List<?>) attribute;
			if (a.size() == 0) {
				session.setAttribute("employees", employeeDao
						.findListByStore(StoreUtils.getStore().getId(),Employee.STATUS_WORKING));
			}
		}
	}
}
